<?php
namespace app\admin\controller;

use app\admin\model\Good as Goods;
use app\admin\model\Category as Categories;
use app\admin\model\ProductImage;
use app\admin\model\ProductProperty;
use think\Request;

class Good extends Base
{
    public function goods_list()
    {

        $goods = Goods::with(['category'])->paginate(10);


        return view('goods/goods-list',[
          'goods'=>$goods
        ]);
    }

    public function goods_add(Request $request)
    {
      if ($request->method() == 'POST') {
          $data = $request->except('type,material,pack,language,one_url,two_url,three_url,four_url,five_url');
          $property = $request->only('type,material,pack,language');
          $imgs = $request->only('one_url,two_url,three_url,four_url,five_url');
          $good = Goods::create($data);
          $imgs['product_id'] = $good->id;
          ProductImage::create($imgs);
          $property['product_id'] = $good->id;
          ProductProperty::create($property);
          if ($good){

              $this->success('添加成功');
          }
          $this->error('添加失败');
      }
        $cates = Categories::all();
        return view('goods/goods-add',[
            'cates'=>$cates
        ]);
    }

    public function goods_edit(Request $request,$id)
    {
        if ($request->method() == 'POST') {
            $data = $request->except('type,material,pack,language,one_url,two_url,three_url,four_url,five_url');
            $property = $request->only('type,material,pack,language');
            $imgs = $request->only('one_url,two_url,three_url,four_url,five_url');
            $good = Goods::update($data);
            ProductProperty::where('product_id',$data['id'])->update($property);
            ProductImage::where('product_id',$data['id'])->update($imgs);
            if ($good){

                $this->success('修改成功');
            }

            $this->error('修改失败');
        }

        $good = Goods::with(['category','property','imgs'])->find($id);
        $cates = Categories::all();

        return view('goods/goods-edit',[
            'good'=>$good,
            'cates'=>$cates
        ]);
    }

    public function goods_delete()
    {

        if (Goods::good_del($_POST['ids'])){

            $this->success('删除成功');

        }else{

            $this->error('删除失败');

        }

    }

    public function ajax_status(Request $request)
    {
        $data = $request->param();
        if (Goods::update($data)){

            $this->success('修改状态成功');
        }else{

            $this->error('修改状态失败');

        }
    }
}
